<template>
    <div>
        <i-card title="上传文件" style="margin-top: 24px">
            <i-row type="flex" justify="space-between">
                <i-col span="17">
                    <i-row type="flex" :gutter="24">
                        <i-col span="4">
                            <Upload action="" accept=".xls,.xlsx" :before-upload="readFile">
                                <Button :disabled="isUploading">导入文件</Button>
                            </Upload>
                        </i-col>
                        <i-col span="5">
                            <Progress v-if="showReadProgress" :percent="readPercent">
                                <span>已导入</span>
                            </Progress>
                        </i-col>
                        <i-col span="15">
                            <i-row justify="end">
                                <i-col>
                                    <Button @click="$router.back()">返回上一页</Button>
                                </i-col>
                            </i-row>
                        </i-col>
                    </i-row>
                    <i-divider size="small" style="margin: 8px 0px;" />
                    <div v-if="file.size">
                        <span>文件名：{{file.name}}</span>
                        <span style="margin-left: 16px;">文件大小：{{file.size}}KB</span>
                        <span style="margin-left: 16px;">修改日期：{{new Date(file.lastModifiedDate).toLocaleString()}}</span>
                        <br>
                        <Button style="margin-top: 5px;" type="primary" :disabled="containError" @click="uploadOrgInfo" :loading="isUploading">导入签到信息</Button>
                        <Progress v-if="showUploadProgress" :percent="uploadPercent"></Progress>
                    </div>
                </i-col>
                <i-col span="5" offset="2">
                    <Steps :current="currentStep" direction="vertical">
                        <Step title="导入Excel" content="选择本地Excel文件"></Step>
                        <Step title="上传签到信息" content="将签到信息上传至服务器，这将花费一些时间"></Step>
                    </Steps>
                </i-col>
            </i-row>
        </i-card>
        <i-card style="margin-top: 16px" title="文件内容">
            <Alert show-icon>
                签到信息Excel填写提醒
                <template slot="desc">是否签到，是否签退两列如不填写将默认为“是”。联系方式列选填。</template>
            </Alert>
            <List>
                <ListItem v-for="(error, index) in errorArray" :key="index">
                    <i-row style="width: 100%">{{error.errLevel}}：{{error.title}}</i-row>
                    <!--template v-slot:action>
                        <i-button v-if="error.type === 101">去除空格（未实现）</i-button>
                    </template-->
                </ListItem>
            </List>
            <i-table :columns="tableTitle" :data="tableData">
                <template v-slot:Order="data">
                    <Tooltip placement="top" :disabled="!data.row.err" :content="data.row.err" transfer max-width="200">
                        <Icon :type="data.row.icon" :color="data.row.color" />{{data.row.学号}}
                    </Tooltip>
                </template>
            </i-table>
        </i-card>
    </div>
</template>

<script>
import excel from '@/../libs/excel'
const axios = require("axios");
export default {
    data () {
        return {
            file: {},
            progressPercent: 0,
            tableData: [],
            tableTitle: [],
            readPercent: 0,
            uploadPercent: 0,
            showReadProgress: false,
            showUploadProgress: false,
            isUploading: false,
            currentStep: 0,
            targetTableHead: [
                "学号", "姓名", "是否签到", "是否签退", "联系方式", "签到时间"
            ],
            errorArray: [],
            containError: false,
            actId: ''
        }
    },
    mounted () {
        this.actId = this.$route.query.actId;
    },
    methods: {
        verifyTable () {
            this.errorArray = [];
            this.containError = false;
            /* 表头部分 */
            if (this.targetTableHead.length !== this.tableTitle.length) {
                this.errorArray.push({
                    errLevel: '错误',
                    title: `表格应有${this.targetTableHead.length}个字段，他们分别是${this.targetTableHead}。但是传入的Excel拥有${this.tableTitle.length}个字段。`,
                    detail: ''
                });
                this.containError = true;
                return;
            }
            for (let index in this.tableTitle) {
                if (this.tableTitle[index].title !== this.targetTableHead[index]) {
                    if (this.tableTitle[index].title.replace(/\s+/g, "") === this.targetTableHead[index]) { // 表头由于空格而不等
                        this.errorArray.push({
                            errLevel: '警告',
                            type: 101,
                            title: `表头第${parseInt(index) + 1}个字段${this.tableTitle[index].title}不应该含有任何空白字符（例如空格等）。`,
                            detail: ''
                        });
                    } else {
                        this.errorArray.push({
                            errLevel: '错误',
                            title: `表头第${parseInt(index) + 1}个字段名应为${this.targetTableHead[index]}而不是${this.tableTitle[index].title}。`,
                            detail: ''
                        });
                        this.containError = true;
                    }
                }
            }
            /* 表格内容 */
            if (this.containError) return; // 表头出错时不继续检查接下来的内容
            for (let index in this.tableData) {
                if (!this.tableData[index].学号) {
                    this.errorArray.push({
                        errLevel: '错误',
                        title: `第${parseInt(index) + 1}项数据的“学号”是必填的。`,
                        detail: ''
                    });
                    this.containError = true;
                }

                if (!this.tableData[index].姓名) {
                    this.errorArray.push({
                        errLevel: '错误',
                        title: `第${parseInt(index) + 1}项数据的“姓名”是必填的。`,
                        detail: ''
                    });
                    this.containError = true;
                }

                if (this.tableData[index].是否签到 !== undefined && this.tableData[index].是否签到 !== '是' && this.tableData[index].是否签到 !== '否') {
                    this.errorArray.push({
                        errLevel: '错误',
                        title: `第${parseInt(index) + 1}项数据的“是否签到”字段的值必须是“是”、“否”、<空白>中的一个。`,
                        detail: ''
                    });
                    this.containError = true;
                }
                if (this.tableData[index].是否签到 === undefined) {
                    this.tableData[index].是否签到 = ""
                }

                if (this.tableData[index].是否签退 !== undefined && this.tableData[index].是否签退 !== '是' && this.tableData[index].是否签退 !== '否') {
                    this.errorArray.push({
                        errLevel: '错误',
                        title: `第${parseInt(index) + 1}项数据的“是否签退”字段的值必须是“是”、“否”、<空白>中的一个。`,
                        detail: ''
                    });
                    this.containError = true;
                }
                if (this.tableData[index].是否签退 === undefined) {
                    this.tableData[index].是否签退 = ""
                }
                if (this.tableData[index].签到时间 === undefined) {
                    this.tableData[index].签到时间 = ""
                }
            }
        },
        readFile (file) {
            this.file = file;
            this.readExcel(file);
            return false;
        },
        // 读取文件
        readExcel (file) {
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onloadstart = e => {
                this.showReadProgress = true;
                this.showUploadProgress = false;
                this.currentStep = 1;
            }
            reader.onprogress = e => {
                this.readPercent = Math.round(e.loaded / e.total * 100);
            }
            reader.onerror = e => {
                this.$Message.error('文件读取出错');
            }
            reader.onload = e => {
                const data = e.target.result;
                const { header, results } = excel.read(data, 'array');

                const tableTitle = header.map(item => { return { title: item, key: item } });

                tableTitle[0].slot = "Order";
                for (let item of results) {
                    item.icon = "";
                }

                this.tableData = results;
                this.tableTitle = tableTitle;
                this.uploadLoading = false;
                this.verifyTable();
            }
        },
        async uploadOrgInfo () {
            this.showUploadProgress = true;
            this.isUploading = true;
            for (let index in this.tableData) {
                this.tableData[index].icon = "md-stopwatch";
                this.tableData[index].color = "#2d8cf0";

                let dic = {
                    '': true,
                    '否': false,
                    '是': true
                }

                let res = await axios.post("/api/activity/SignInByImport", {
                    id: this.actId,
                    code: this.tableData[index].学号,
                    name: this.tableData[index].姓名,
                    isSignEnter: dic[this.tableData[index].是否签到],
                    isSignLeave: dic[this.tableData[index].是否签退],
                    mobile: this.tableData[index].联系方式,
                    date: this.tableData[index].签到时间
                });
                this.uploadPercent = Math.round((parseInt(index) + 1) / this.tableData.length * 100);
                if (res.data.success) {
                    this.tableData[index].icon = "md-checkmark";
                    this.tableData[index].color = "#19be6b";
                } else {
                    this.tableData[index].icon = "md-close";
                    this.tableData[index].color = "#ed4014";
                    this.tableData[index].err = res.data.msg;
                }
            }
            await axios.postStream("/api/activity/CompleteActivity", {id: this.actId, State: 1});
            this.currentStep = 2;
            this.isUploading = false;
        }
    }
};
</script>

<style>
</style>
